<template>
    <div>
      <Operation @add="add">公告发布</Operation>
      <!-- 数据表格 -->
      <el-scrollbar class="com_table">
        <el-table :data="formData" style="width: 100%">
          <el-table-column prop="title" label="公告标题" width="250" />
          <el-table-column prop="content" label="公告内容" />
          <el-table-column width="180" label="编辑/删除">
            <template #default="scope">
              <el-button @click="edit(scope.row.id)" size="small" type="primary">编辑</el-button>
              <el-button @click="del(scope.row.id)" size="small" type="danger">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
      <!-- 分页栏 -->
      <div class="pagination">
        <el-pagination background :default-page-size="listCount" layout="prev, pager, next" :total="totalCount"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </template>
  
  <script setup>
  import Operation from '@/components/operation.vue'
  import { watch, inject, ref } from 'vue'
  import { useRouter } from 'vue-router'
  const router = useRouter()
  const $root = inject('$root')
  /* 页面表格数据 */
  let formData = ref([])
  const $axios = inject('$axios')
  /* 定义总数据条数 */
  let totalCount = ref(0)
  /* 定义每页显示的数据条数 */
  let listCount = 10
  /* 获取页面数据 */
  const getPageData = (pageNO = 1) => {
    $axios.get($root + `/notice/?page=${pageNO}&page_size=${listCount}`)
      .then(r => {
        console.log(r)
        if (r.data.code == 200) {
          formData.value = r.data.data.data
          totalCount.value = r.data.data.total_count
        }
      })
  }
  
  /* 分页栏功能 */
  const handleCurrentChange = (e)=>{
      /* e为当前页 */
      getPageData(e)
  }
  
  /* 删除数据 */
  const del = (id)=>{
    $axios.post($root+`/notice/delete/${id}/`)
    .then(r=>{
      if(r.data.code==200){
        getPageData()
        ElMessage({
            message: '删除数据成功',
            type: 'success',
          })
      }
      else{
        ElMessage.error('删除数据失败')
      }
    })
  }
  
  /* 添加数据 */
  const add = ()=>{
    router.push(`/home/noticedetail`)
  }
  
  /* 编辑数据 */
  const edit = (id)=>{
    router.push(`/home/noticedetail/${id}`)
  }
  
  
  watch(() => router.currentRoute.value.name, (name) => {
    if (name == "notice") {
      getPageData()
    }
  }, { immediate: true, deep: true })
  
  </script>
  
  <style scoped>
  .pagination {
    display: flex;
    justify-content: center;
    margin-top: 15px;
  }
  </style>